using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DesktopHelper.Data;
using DesktopHelper.Models;
using DesktopHelper.Views;

namespace DesktopHelper.Services
{
    public class PinnedImageService
    {
        private readonly ILogger<PinnedImageService> _logger;
        private readonly DatabaseService _databaseService;
        private readonly List<PinnedImageWindow> _pinnedWindows = new();

        public PinnedImageService(ILogger<PinnedImageService> logger, DatabaseService databaseService)
        {
            _logger = logger;
            _databaseService = databaseService;
        }

        /// <summary>
        /// 将图片钉到桌面
        /// </summary>
        public async Task<PinnedImageWindow?> PinImageToDesktop(string imagePath, int x = -1, int y = -1)
        {
            try
            {
                // 创建钉图窗口
                var pinnedWindow = new PinnedImageWindow(imagePath);
                
                // 设置位置
                if (x >= 0 && y >= 0)
                {
                    pinnedWindow.Left = x;
                    pinnedWindow.Top = y;
                }
                else
                {
                    // 默认位置（屏幕中央偏移）
                    var offsetCount = _pinnedWindows.Count * 20;
                    pinnedWindow.Left = (System.Windows.SystemParameters.PrimaryScreenWidth - pinnedWindow.Width) / 2 + offsetCount;
                    pinnedWindow.Top = (System.Windows.SystemParameters.PrimaryScreenHeight - pinnedWindow.Height) / 2 + offsetCount;
                }

                // 显示窗口
                pinnedWindow.Show();
                
                // 添加到管理列表
                _pinnedWindows.Add(pinnedWindow);
                
                // 注册事件
                pinnedWindow.Closed += (s, e) => OnPinnedWindowClosed(pinnedWindow);
                pinnedWindow.PositionChanged += OnPinnedWindowPositionChanged;
                pinnedWindow.OpacityChanged += OnPinnedWindowOpacityChanged;

                // 保存到数据库
                var pinnedImage = new PinnedImage
                {
                    ImagePath = imagePath,
                    X = (int)pinnedWindow.Left,
                    Y = (int)pinnedWindow.Top,
                    Width = (int)pinnedWindow.Width,
                    Height = (int)pinnedWindow.Height,
                    Opacity = pinnedWindow.Opacity,
                    CreateTime = DateTime.Now,
                    IsVisible = true
                };

                pinnedImage.Id = await _databaseService.InsertPinnedImageAsync(pinnedImage);
                pinnedWindow.PinnedImageId = pinnedImage.Id;

                _logger.LogInformation("图片已钉到桌面: {ImagePath}", imagePath);
                return pinnedWindow;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "钉图失败: {ImagePath}", imagePath);
                return null;
            }
        }

        /// <summary>
        /// 关闭指定的钉图
        /// </summary>
        public void ClosePinnedImage(int pinnedImageId)
        {
            try
            {
                var window = _pinnedWindows.FirstOrDefault(w => w.PinnedImageId == pinnedImageId);
                window?.Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "关闭钉图失败: {PinnedImageId}", pinnedImageId);
            }
        }

        /// <summary>
        /// 关闭所有钉图
        /// </summary>
        public void CloseAllPinnedImages()
        {
            try
            {
                var windows = _pinnedWindows.ToList();
                foreach (var window in windows)
                {
                    window.Close();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "关闭所有钉图失败");
            }
        }

        /// <summary>
        /// 获取所有活动的钉图窗口
        /// </summary>
        public List<PinnedImageWindow> GetActivePinnedWindows()
        {
            return _pinnedWindows.ToList();
        }

        /// <summary>
        /// 设置钉图透明度
        /// </summary>
        public void SetPinnedImageOpacity(int pinnedImageId, double opacity)
        {
            try
            {
                var window = _pinnedWindows.FirstOrDefault(w => w.PinnedImageId == pinnedImageId);
                if (window != null)
                {
                    window.Opacity = Math.Max(0.1, Math.Min(1.0, opacity));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置钉图透明度失败: {PinnedImageId}", pinnedImageId);
            }
        }

        /// <summary>
        /// 恢复上次会话的钉图
        /// </summary>
        public async Task RestorePinnedImagesAsync()
        {
            try
            {
                // 从数据库获取所有可见的钉图
                using var connection = new Microsoft.Data.Sqlite.SqliteConnection(
                    $"Data Source={System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DesktopHelper", "DesktopHelper.db")}");
                await connection.OpenAsync();

                var sql = "SELECT * FROM PinnedImages WHERE IsVisible = 1";
                using var command = new Microsoft.Data.Sqlite.SqliteCommand(sql, connection);
                using var reader = await command.ExecuteReaderAsync();

                while (await reader.ReadAsync())
                {
                    var pinnedImage = new PinnedImage
                    {
                        Id = reader.GetInt32(0), // Id
                        ImagePath = reader.GetString(1), // ImagePath
                        X = reader.GetInt32(2), // X
                        Y = reader.GetInt32(3), // Y
                        Width = reader.GetInt32(4), // Width
                        Height = reader.GetInt32(5), // Height
                        Opacity = reader.GetDouble(6), // Opacity
                        CreateTime = reader.GetDateTime(7), // CreateTime
                        IsVisible = reader.GetBoolean(8) // IsVisible
                    };

                    // 检查图片文件是否仍然存在
                    if (System.IO.File.Exists(pinnedImage.ImagePath))
                    {
                        await PinImageToDesktop(pinnedImage.ImagePath, pinnedImage.X, pinnedImage.Y);
                    }
                    else
                    {
                        // 如果文件不存在，从数据库中删除记录
                        var deleteCommand = new Microsoft.Data.Sqlite.SqliteCommand(
                            "DELETE FROM PinnedImages WHERE Id = @Id", connection);
                        deleteCommand.Parameters.AddWithValue("@Id", pinnedImage.Id);
                        await deleteCommand.ExecuteNonQueryAsync();
                    }
                }

                _logger.LogInformation("已恢复 {Count} 个钉图", _pinnedWindows.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复钉图失败");
            }
        }

        private void OnPinnedWindowClosed(PinnedImageWindow window)
        {
            try
            {
                _pinnedWindows.Remove(window);
                
                // 从数据库中删除或标记为不可见
                if (window.PinnedImageId > 0)
                {
                    _ = Task.Run(async () =>
                    {
                        try
                        {
                            using var connection = new Microsoft.Data.Sqlite.SqliteConnection(
                                $"Data Source={System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DesktopHelper", "DesktopHelper.db")}");
                            await connection.OpenAsync();

                            var sql = "UPDATE PinnedImages SET IsVisible = 0 WHERE Id = @Id";
                            using var command = new Microsoft.Data.Sqlite.SqliteCommand(sql, connection);
                            command.Parameters.AddWithValue("@Id", window.PinnedImageId);
                            await command.ExecuteNonQueryAsync();
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "更新钉图状态失败");
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理钉图窗口关闭失败");
            }
        }

        private void OnPinnedWindowPositionChanged(object? sender, EventArgs e)
        {
            if (sender is PinnedImageWindow window && window.PinnedImageId > 0)
            {
                _ = Task.Run(async () =>
                {
                    try
                    {
                        // 在UI线程上获取窗口位置
                        var position = await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            return new { Left = (int)window.Left, Top = (int)window.Top, Id = window.PinnedImageId };
                        });
                        
                        using var connection = new Microsoft.Data.Sqlite.SqliteConnection(
                            $"Data Source={System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DesktopHelper", "DesktopHelper.db")}");
                        await connection.OpenAsync();

                        var sql = "UPDATE PinnedImages SET X = @X, Y = @Y WHERE Id = @Id";
                        using var command = new Microsoft.Data.Sqlite.SqliteCommand(sql, connection);
                        command.Parameters.AddWithValue("@X", position.Left);
                        command.Parameters.AddWithValue("@Y", position.Top);
                        command.Parameters.AddWithValue("@Id", position.Id);
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "更新钉图位置失败");
                    }
                });
            }
        }

        private void OnPinnedWindowOpacityChanged(object? sender, EventArgs e)
        {
            if (sender is PinnedImageWindow window && window.PinnedImageId > 0)
            {
                _ = Task.Run(async () =>
                {
                    try
                    {
                        // 在UI线程上获取窗口透明度
                        var opacity = await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            return new { Opacity = window.Opacity, Id = window.PinnedImageId };
                        });
                        
                        using var connection = new Microsoft.Data.Sqlite.SqliteConnection(
                            $"Data Source={System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DesktopHelper", "DesktopHelper.db")}");
                        await connection.OpenAsync();

                        var sql = "UPDATE PinnedImages SET Opacity = @Opacity WHERE Id = @Id";
                        using var command = new Microsoft.Data.Sqlite.SqliteCommand(sql, connection);
                        command.Parameters.AddWithValue("@Opacity", opacity.Opacity);
                        command.Parameters.AddWithValue("@Id", opacity.Id);
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "更新钉图透明度失败");
                    }
                });
            }
        }
    }
}